import json
from django.shortcuts import render

from apps.oauth.models import OAuthQQUser
from apps.users.models import User

# Create your views here.
"""
前端：用户点击qq登陆按钮，发送axios请求

路由: GET  
后端：业务逻辑：调用qqlogintool 生成跳转连接
     返回跳转连接 json({
         "code":0,
         "qq_login_url":xxx
     })
"""

from QQLoginTool.QQtool import OAuthQQ
from django.views import View
from django.http import HttpRequest, JsonResponse
from meiduo_mall import settings
class qqloginview(View):
    """qq登陆视图"""
    def get(self, request:HttpRequest):
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, 
                        client_secret=settings.QQ_CLIENT_SECRET, 
                        redirect_uri=settings.QQ_REDIRECT_URI, 
                        state="xxxx")
        # 生成跳转连接
        login_url = oauth.get_qq_url()
        print(login_url)
        # 返回响应
        return JsonResponse({
            "code": 0,
            "login_url": login_url
        })
        
        
"""
需求， 获取code,通过code获取access_token,通过access_token获取openid
前端：获取用户同意登陆的code,并把code发送给后端
后端：步骤1.获取code
      步骤2.通过code获取access_token   
        步骤3.通过access_token获取openid
        步骤4.根据openid查询数据库，如果存在，说明是老用户，直接登陆
        步骤5.如果不存在，说明是新用户，需要绑定
     
     
"""
from django.contrib.auth import login
class OAuthQQView(View):
    def get(self, request: HttpRequest):
    #     步骤1.获取code
        code = request.GET.get("code")
        if not code:
            return JsonResponse({"code": 400, "errmsg": "缺少code参数"})
        
    #   步骤2.通过code获取access_token   
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state="xxxx")
        access_token = oauth.get_access_token(code)
        if not access_token:
            return JsonResponse({"code": 400, "errmsg": "获取access_token失败"})
        
        
    #     步骤3.通过access_token获取openid
        openid = oauth.get_open_id(access_token)
        if not openid:
            return JsonResponse({"code": 400, "errmsg": "获取openid失败"})
        
    #     步骤4.根据openid查询数据库，如果存在，说明是老用户，直接登陆
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            response  = JsonResponse({"code": 400, "access_token": openid})
            return response
        else:
            #存在
            #设置session
            login(request, qquser.user)
            # 设置cookie
            response = JsonResponse({"code": 0, "errmsg": "登陆成功"})
            response.set_cookie("username", qquser.user.username)
            from apps.carts.utils import merge_cart_cookie_to_redis
            response = merge_cart_cookie_to_redis(request=request, user=qquser.user, response=response)
            return response
    def post(self, request: HttpRequest):
        """绑定手机号"""
        # 1.接收请求&获取参数    
        data = json.loads(request.body.decode())
        mobile = data.get("mobile")
        sms_code = data.get("sms_code")    
        password = data.get("password")
        openid = data.get("access_token")
        # 2.参数校验（省略）
        if not all([mobile, sms_code, openid]):
            return JsonResponse({"code": 400, "errmsg": "缺少参数"})
        # 3.根据手机号查询用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:   
            # 4.如果用户不存在，创建新用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 5.如果用户存在，校验密码
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "密码错误"})
        # 6.绑定openid
        OAuthQQUser.objects.create(openid=openid, user=user)
        # 7.设置session
        login(request, user)
        # 8.设置cookie,返回相应
        response = JsonResponse({"code": 0, "errmsg": "绑定成功"})
        response.set_cookie("username", user.username)
        return response
        
            
        
        

"""
测试git回滚

"""
"""
测试新分支
"""